/* =========================================================================
 *
 *   The traffic processor. v.0.0.1 (rc)
 *
 *   Development by Sedelnikov Alexander (Bigking).
 *
 * =========================================================================
 */

#include "job_manager.h"
#include "log.h"
#include "transact.h"


#define LOCK_FILE "./trfprc.pid"
#define CFG_FILE  "./trfprc.conf"


//-----------------------------------------------------------------------//
int main( int argc, char *argv[] )
{
    FILE *fp;

    try
    {
        if( argc == 1 )
            cconfig::set_file_name( CFG_FILE );
        else
            cconfig::set_file_name( argv[ 1 ] );

        cconfig::parse();

        // Protector.
        ulong        cur_pid = 0;

        fp = fopen( cconfig::get_pid_file(), "rb" );
        if( fp != NULL )
        {
            fscanf( fp, "%ld", &cur_pid );
            fclose( fp );

            if( cur_pid && cprocess::pid_exist( cur_pid ) )
            {
                logwrn( "Process is running! [Duplicated]" );
                return 0;
            }
        }

        fp = fopen( cconfig::get_pid_file(), "wb" );

        if( fp == NULL )
        {
            logfatal( "Can't create lock file! [ %s ]", cconfig::get_pid_file() );
            return 1;
        }

        fprintf( fp, "%ld", cprocess::get_pid() );

        fclose( fp );



        logline;
        ctransaction::check_xlog();
        cjob_manager::do_job();
    }
    catch( cexception &exc )
    {
        logfatal( exc.get_formated_message() );
        cconfig::release();
        return 1;
    }

    fp = fopen( cconfig::get_pid_file(), "wb" );
    if( fp != NULL )
        fclose( fp );

    logmsg( "Job is complite." );
    cconfig::release();

    return 0;
}
